﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    public float speed = 5;
    private Rigidbody2D _rigidbody2D;
    private Animator _animatior;

    private float x;
    private float y;
    void Start()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
        _animatior = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        x = Input.GetAxis("Horizontal");
        y = Input.GetAxis("Vertical");

        // 正向
        if (x > 0) 
        {
            _rigidbody2D.transform.eulerAngles = new Vector3(x: 0, y: 0, z: 0);
            _animatior.SetBool("run", true);
        }

        // 欧拉角转向180度，反方向朝向
        if (x < 0)
        {
            _rigidbody2D.transform.eulerAngles = new Vector3(x: 0, y: 180f, z: 0);
            _animatior.SetBool("run", true);
        }

        // 静止状态， x不会完全等于0， 在较小的范围内取值 
        if (x < 0.001f && x > -0.001f) 
        {
            _animatior.SetBool("run", false);
        }

        Run();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.tag=="Spike" ||
           collision.gameObject.tag == "Saw")
        {
            GameController.Instance.ShowGameOverPanel();
            Destroy(gameObject);
        }
      
    }
    private void Run()
    {
        Vector3 movement = new Vector3(x, y, z: 0);
        _rigidbody2D.transform.position += movement * speed * Time.deltaTime;
    }
}
